有時某些 HTML 的排版十分雷同,此時 Flask 當中的 Jinja 就提供了模板繼承的功能,可以讓你把重複的地方當作模板,至於每一個 HTML 確切要什麼的話在自己加入,十分方便的功能,在這邊分享給大家~
# index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {% block setting %}
    <title>Document</title>
    {% endblock %}
</head>
<body>
    {% block main %}
    <h1>歡迎來到 Kyle Kao 的 Ithome 鐵人賽</h1>
    {% endblock %}
</body>
</html>
{% block 區塊名 %} {% endblock %} 給包起來,以上面為例,這邊包了兩個地方,並且分別命名為 setting 和 main。% 包起來,很常會少括導致錯誤產生,這邊要小心。# enter.html
{% extends "index.html" %}
{% block setting %} {{super()}} {% endblock %}
{% block main %} 
    {{super()}}
    <form action="" method="post">
        <input type="text" name="name" placeholder="請輸入名字"> <br \> <br \>
        <input type="text" name="age" placeholder="請輸入年齡"> <br \> <br \>
        <input type="submit">
    </form> 
{% endblock %}
# welcome.html
{% extends "index.html" %}
{% block setting %} {{super()}} {% endblock %}
{% block main %} 
    {{super()}} 
    <p>welcome {{name}} {{age}} years old</p>
{% endblock %}
{% extends "模板.html" %}。以上面為例為 {% extends "index.html" %}
{% block 區塊名 %} {% endblock %},並且若想要直接套入模塊裡面原先有的內容則填入 {{super()}},這樣就會把模版當中原先有的值也填入進去。以上面為例為 {% block setting %} {{super()}} {% endblock %}。# app.py
from flask import Flask, request, redirect, render_template, url_for
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        name = request.values['name']
        age = request.values['age']
        return redirect(url_for('welcome', name = name, age = age))
    return render_template('enter.html') 
@app.route('/welcome/<name>/<age>')
def welcome(name, age):
    return render_template('welcome.html', name = name, age = age)